<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :append-to-body="true"
    :visible.sync="showDialog"
    :width="isLeave && status == 1 && lastCheckNum == 1 && handleType == 1 ? '620px' : '400px'"
    @close="hiddenView">
    <div
      v-if="status == 1 && detail.examineType == 2"
      class="handle-type">
      <flexbox class="handle-item">
        <el-radio
          v-model="handleType"
          :label="1"><span/></el-radio>
        <div
          style="font-size: 12px;"
          @click.native="handleType=1">审核结束</div>
      </flexbox>
      <flexbox
        id="selectUser"
        class="handle-item">
        <el-radio
          v-model="handleType"
          :label="2"><span/></el-radio>
        <xh-user-cell
          class="select-user"
          placeholder="选择下一审批人"
          @focus="selectUserFocus"
          @value-change="selectExamineUser"/>
      </flexbox>
    </div>
    <div
      v-if="status == 1 && detail.examineType == 2"
      class="title">意见</div>
    <el-input
      v-model="content"
      :rows="5"
      :maxlength="200"
      :placeholder="placeholder"
      type="textarea"
      resize="none"
      show-word-limit/>

    <div v-if="status==1 && handleType==1 && (examineType==='crm_leads' || examineType==='crm_customer') && lastCheckNum==1" class="handle-type">
      <flexbox class="handle-item">
        <div class="handle-item-name">客户类型：</div>
        <el-radio v-model="customerType" :label="1" border size="small" >潜在客户</el-radio>
        <el-radio v-model="customerType" :label="2" border size="small">目标客户</el-radio>
        <!-- <xh-user-cell
          class="select-user"
          placeholder="点击选择"
          @value-change="userChage"/> -->
      </flexbox>
    </div>
    <div v-if="status==1 && handleType==1 && examineType==='crm_leads' && lastCheckNum==1" class="handle-type">
      <flexbox class="handle-item">
        <div class="handle-item-name">客户负责人：</div>
        <xh-user-cell
          class="select-user"
          placeholder="点击选择"
          :value="defaultOwnerUser"
          @value-change="userChage"/>
      </flexbox>
    </div>
    <div v-if="status==1 && handleType==1 && examineType=='crm_preSales' && lastCheckNum==1" class="handle-type">
      <flexbox class="handle-item">
        <div class="handle-item-name">售前负责人：</div>
        <xh-user-cell
          class="select-user"
          placeholder="点击选择"
          @value-change="userChage"/>
      </flexbox>
    </div>
    <div v-if="status==1" class="handle-type">
      <flexbox class="handle-item">
        <div class="handle-item-name">附件清单：</div>
        <xh-files
          class="select-user"
          placeholder="点击上传"
          @value-change="fileUpload"
          />
      </flexbox>
    </div>
    <div
      v-if="status == 1 && canAddUser"
      class="handle-type">
      <flexbox
        class="handle-item">
        <div class="handle-item-name">选择审批人：</div>
        <xh-user-cell
          class="select-user"
          placeholder="选择下一审批人"
          @focus="selectUserFocus"
          @value-change="selectExamineUser"/>
      </flexbox>
    </div>
    <div v-if="isLeave && status == 1 && lastCheckNum == 1 && handleType == 1">
      <el-form :inline="true" :model="express" class="demo-form-inline">
        <el-form-item label="物流单号">
          <el-input v-model="express.express_num" placeholder="物流单号"></el-input>
        </el-form-item>
        <el-form-item label="物流公司">
          <el-select v-model="express.express_name" placeholder="物流公司">
            <el-option label="圆通" value="圆通"></el-option>
            <el-option label="顺丰" value="顺丰"></el-option>
            <el-option label="中通" value="中通"></el-option>
            <el-option label="申通" value="申通"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="isLeave && status == 1 && lastCheckNum == 1 && handleType == 1">
      <store-product
        ref="storeProductCom"
        :action="{id:id}"
        :psi-type="psiType"
        :isenter="false"
        :isleave="isLeave"
        :checkFinal="checkFinal"
        :storehouse="storehouseId"></store-product>
    </div>
    <div
      slot="footer"
      class="dialog-footer">
      <el-button @click="handleClick('cancel')">取 消</el-button>
      <el-button v-if="status==1 && handleType==1 && examineType==='crm_leads' && lastCheckNum==1" @click="handleClick('seas')">放入公海</el-button>
      <el-button
        type="primary"
        @click="handleClick('confirm')">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script type="text/javascript">
import { crmExamineFlowAuditExamine } from '@/api/customermanagement/common'
import { oaExamineFlowAuditExamine } from '@/api/oamanagement/examine'
import { psiExamineFlowAuditExamine } from '@/api/psimanagement/common'

import { XhUserCell } from '@/components/CreateCom'
import { XhFiles } from '@/components/CreateCom'
import StoreProduct from '@/components/CreateCom/StoreProduct'
export default {
  name: 'ExamineHandle', // 合同审核操作
  components: {
    XhUserCell,
    XhFiles,
    StoreProduct
  },
  props: {
    show: {
      type: Boolean,
      default: false
    }, // 审核状态 1 审核通过 2 审核拒绝 4 已撤回
    /** 操作类型  1通过0拒绝2撤回*/ status: {
      type: [String, Number],
      default: 1
    },
    // 详情信息id
    id: [String, Number],
    // 仓库id
    storehouseId: {
      type: [String, Number],
      default: ''
    },
    // 出入库id
    elsId: {
      type: [String, Number],
      default: ''
    },
    recordId: [String, Number],
    // 审核信息 config 1 固定 0 自选
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // crm_contract crm_receivables oa_examine
    examineType: {
      type: String,
      default: ''
    },
    lastCheckNum: {
      type: Number,
      default: 1
    },
    canAddUser: {
      type: Boolean,
      default: false
    },
    // 业务详细信息
    relativeData: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      loading: false,
      showDialog: false,
      handleType: 1,
      selectUsers: [],
      usersList: [],
      content: '', // 输入内容
      // sureOrCustom: this.examineType == 'crm_leads' && this.status == 1 ? '转化为客户' : '确定',
      batchId: '',
      // 物流信息
      express: {
        'express_name': '',
        'express_num': ''
      },
      psiType: '',
      checkFinal: true,
      defaultOwnerUser:[],
      customerType: 2
    }
  },
  computed: {
    title() {
      if (this.status == 1) {
        return '审批通过'
      } else if (this.status == 2) {
        return '审批拒绝'
      } else if (this.status == 4) {
        return '撤回审批'
      }
      return ''
    },
    placeholder() {
      // 1 审核通过 2 审核拒绝 4 已撤回
      if (this.status == 1) {
        return '请输入审批意见（选填）'
      } else if (this.status == 2) {
        return '请输入审批意见（必填）'
      } else if (this.status == 4) {
        return '请输入撤回理由（必填）'
      }
      return ''
    },
    isLeave() {
      if (
        this.psiType == 'salesLeave' ||
        this.psiType == 'borrowLeave' ||
        this.psiType == 'repairLeave' ||
        this.psiType == 'testLeave' ||
        this.psiType == 'otherLeave'
      ) {
        return true
      }
      return false
    }
  },
  watch: {
    show: {
      handler(val) {
        this.showDialog = val
      },
      deep: true,
      immediate: true
    },
    examineType: {
      handler(val) {
        var index = val.lastIndexOf('\_')
        this.psiType = val.substring(index + 1, val.length)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    if(this.examineType === 'crm_leads' || this.examineType === 'crm_customer'){
      this.customerType = this.relativeData.customerType;
      if(this.relativeData.ownerUserId){
        this.defaultOwnerUser = [{userId: this.relativeData.ownerUserId,realname: this.relativeData.ownerUserName}];
        this.usersList = [{userId: this.relativeData.ownerUserId,realname: this.relativeData.ownerUserName}];
      }
    }

  },
  methods: {
    submitInfo(type) {
      if ((this.status == 2 || this.status == 4) && !this.content) {
        this.$message.error(this.placeholder)
      } else {
        if (this.status == 2 || this.status == 1) {
          // 1通过0拒绝2撤回
          // this.getDetail()
          this.handlePassAndReject(type)
        } else if (this.status == 4) {
          this.handleRevoke()
        }
      }
    },
    // 撤回操作
    handleRevoke() {
      this.loading = true
      this.getRequest()({
        id: this.id,
        recordId: this.recordId,
        status: this.status,
        batchId: this.batchId,
        remarks: this.content
      })
        .then(res => {
          this.loading = false
          this.$message.success('操作成功')
          this.$emit('save')
          this.$bus.emit('examine-handle-bus')
          this.$store.dispatch('GetMessageNum')
          this.hiddenView()
        })
        .catch(() => {
          this.loading = false
        })
    },
    getRequest() {
      return {
        crm_customer: crmExamineFlowAuditExamine,
        crm_leads: crmExamineFlowAuditExamine,
        crm_contract: crmExamineFlowAuditExamine,
        crm_receivables: crmExamineFlowAuditExamine,
        crm_business: crmExamineFlowAuditExamine,
        crm_preSales: crmExamineFlowAuditExamine,
        crm_quotation: crmExamineFlowAuditExamine,
        oa_examine: oaExamineFlowAuditExamine,
        crm_officePurchase: crmExamineFlowAuditExamine,
        crm_normalPurchase: crmExamineFlowAuditExamine,
        crm_projectPurchase: crmExamineFlowAuditExamine,
        crm_devPurchase: crmExamineFlowAuditExamine,
        crm_otherPurchase: crmExamineFlowAuditExamine,
        crm_salesEnter: psiExamineFlowAuditExamine,
        crm_purchaseEnter: psiExamineFlowAuditExamine,
        crm_retrunEnter: psiExamineFlowAuditExamine,
        crm_repairEnter: psiExamineFlowAuditExamine,
        crm_testEnter: psiExamineFlowAuditExamine,
        crm_inventoryProfitEnter: psiExamineFlowAuditExamine,
        crm_otherEnter: psiExamineFlowAuditExamine,
        crm_salesLeave: psiExamineFlowAuditExamine,
        crm_borrowLeave: psiExamineFlowAuditExamine,
        crm_repairLeave: psiExamineFlowAuditExamine,
        crm_testLeave: psiExamineFlowAuditExamine,
        crm_inventoryLossLeave: psiExamineFlowAuditExamine,
        crm_otherLeave: psiExamineFlowAuditExamine
      }[this.examineType]
    },
    // 通过 拒绝操作
    handlePassAndReject(type) {
      this.loading = true
      var params = {
        id: this.id,
        recordId: this.recordId,
        status: this.status,
        batchId: this.batchId,
        remarks: this.content
      }
      if (this.status == 1 && this.detail.examineType == 2) {
        if (this.handleType != 1) {
          if (this.selectUsers[0] == undefined) {
            this.loading = false
            this.$message.error('请选择下一审批人')
            return false
          }
          params['nextUserId'] = this.selectUsers[0].userId
        }
      }
      if (this.status == 1 && this.detail.examineType == 1 && this.canAddUser) {
        if (this.selectUsers.length > 0) {
          params['checkUserId'] = this.selectUsers[0].userId
        }
      }

      // if (this.status == 1 && this.detail.examineType == 1 && this.examineType === 'crm_quotation') {
      //   if(this.relativeData.reviewPrice === 1 || this.relativeData.reviewRate === 1){
      //     params['checkUserId'] = 3
      //   }
      // }
      if (this.status == 1 && this.lastCheckNum == 1 && this.handleType == 1) {
        if(this.examineType === 'crm_leads'){
          if (type == 'confirm') {
            if (this.usersList[0] == undefined) {
              this.loading = false
              this.$message.error('请选择客户负责人')
              return false
            }
            params['newOwnerId'] = this.usersList[0].userId
            params['customerType'] = this.customerType
          } else if (type == 'seas') {
            params['newOwnerId'] = 0
          }
        }
        if(this.examineType === 'crm_customer'){
          params['customerType'] = this.customerType
        }
        if(this.examineType === 'crm_preSales'){
          if (type == 'confirm') {
            if (this.usersList[0] == undefined) {
              this.loading = false
              this.$message.error('请选择售前负责人')
              return false
            }
            params['newOwnerId'] = this.usersList.length ? this.usersList[0].userId : null
          }
        }
        if (this.isLeave) {
          var productData = this.$refs.storeProductCom.ruleForm.tableData
          var newProduct = []
          for (var j = 0; j < productData.length; j++) {
            productData[j].elsQuantity = Number(productData[j].elsQuantity)
            if (productData[j].upcCode.length > 1) {
              for (var i = 0; i < productData[j].upcCode.length; i++) {
                if (productData[j].upcCodeUniqueFlag === 1 && productData[j].upcCode[i].barcode == '') {
                  this.loading = false
                  this.$message.error('请输入产品条码')
                  return
                }
                var itemProduct = JSON.parse(JSON.stringify(productData[j]))
                itemProduct.upcCode = ''
                itemProduct.upcCode = productData[j].upcCode[i].barcode
                itemProduct.elsQuantity = 1
                newProduct.push(itemProduct)
              }
            } else {
              if (productData[j].upcCode[0].barcode != '') {
                productData[j].upcCode = productData[j].upcCode[0].barcode
              } else {
                if (productData[j].upcCodeUniqueFlag === 1) {
                  this.loading = false
                  this.$message.error('请输入产品条码')
                  return
                }
                productData[j].upcCode = ''
              }
              newProduct.push(productData[j])
            }
            delete productData[j].productNameData
          }
          var productData = {
            products: newProduct,
            entity: {
              els_id: this.id,
              express_name: this.express.express_name,
              express_num: this.express.express_num
            }
          }
          params['data'] = JSON.stringify(productData)
        }
      }
      this.getRequest()(params)
        .then(res => {
          this.loading = false
          if (res.msg) {
            this.$message.warning(res.msg)
          } else {
            this.$message.success('操作成功')
          }
          this.$emit('save', { type: this.status })
          this.hiddenView()
          this.$bus.emit('examine-handle-bus')
          this.$store.dispatch('GetMessageNum')
          this.$store.dispatch('GetPsiMessageNum')
          this.$store.dispatch('GetFinanceMessageNum')
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleClick(type) {
      if (type == 'cancel') {
        this.hiddenView()
      } else if (type == 'confirm' || type == 'seas') {
        this.submitInfo(type)
      }
    },
    /** 选择了下一审批人 */
    selectUserFocus() {
      this.handleType = 2
    },
    selectExamineUser(data) {
      this.selectUsers = data.value
    },
    hiddenView() {
      this.$emit('close')
    },
    // 通过时选择客户的负责人
    userChage(data) {
      this.usersList = data.value
    },

    //审核通过时，可选择上传文件
    fileUpload(data){
      this.batchId = data.batchId;
    }
  }
}
</script>
<style lang="scss" scoped>
.handle-type {
  padding-bottom: 8px;
  .handle-item {
    padding: 8px 0;
    cursor: pointer;
  }
}

.el-dialog__wrapper /deep/ .el-dialog__body {
  padding: 10px 25px 20px;
}

.el-radio-group /deep/ .el-radio + .el-radio {
  margin-left: 0px;
}

.select-user {
  flex: 1;
}

.title {
  font-size: 12px;
  padding-bottom: 8px;
  color: #666;
}

.handle-item-name{
  min-width: 100px;
}
</style>
